<template>
  <div>
    <div>
      <el-row>
        <el-col :span="9">
          <el-form-item label="任务名称" prop="taskName">
            <el-input
              v-model="form.taskName"
              :disabled="dialogType<2"
              placeholder="请输入任务名称"
              style="width: 204px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="数据迁移方式" prop="transferType">
            <el-button type="primary">卸数</el-button>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="是否数据分析" prop="isDataAnalysis">
            <el-checkbox v-model="form.isDataAnalysis" :disabled="dialogType<2" true-label="Y" fales="N" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.tableSelectType === '直连'">
        <el-col :span="9">
          <el-form-item label="服务器名称" prop="sourceConnPkId">
            <el-select v-model="form.sourceConnPkId" filterable :disabled="dialogType<2" placeholder="请选择" @change="dataSourceConnChange">
              <el-option
                v-for="item in sourceConnList"
                :key="item.pkId"
                :label="item.sourceName"
                :value="item.pkId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="数据库名称" prop="database">
            <el-select v-model="form.database" filterable :disabled="dialogType<2" placeholder="请选择">
              <el-option v-for="database in sourceDatabaseList" :key="database" :label="database" :value="database" />
            </el-select>
          </el-form-item>
          <el-button
            style="margin-left: 25px;"
            class="bordered-button"
            :disabled="form.sourceConnPkId === null || form.database === null"
            size="medium"
            type="text"
            @click="showAllTableList"
          >展示卸数表清单
          </el-button>

        </el-col>
      </el-row>
      <el-row style="margin-bottom: 10px">
        <el-col :span="3">
          <el-input v-model.trim="querySourceDatabaseName" placeholder="请输入源库名" />
        </el-col>
        <el-col :span="3" style="margin: 0 10px">
          <el-input v-model.trim="querySourceTableName" placeholder="请输入源表名" />
        </el-col>
        <el-col :span="3">
          <el-input v-model.trim="queryTargetDatabaseName" placeholder="请输入目标库名" />
        </el-col>
        <el-col :span="3" style="margin-left: 10px">
          <el-input v-model.trim="queryTargetTableName" placeholder="请输入目标表名" />
        </el-col>
        <el-button
          class="filter-item"
          size="mini"
          style="margin-left: 5px"
          type="success"
          icon="el-icon-search"
          @click="toQuery"
        >搜索
        </el-button>
        <el-button class="filter-item" size="mini" type="warning" icon="el-icon-refresh-left" @click="resetQuery">重置
        </el-button>
        <el-button class="filter-item" type="danger" icon="el-icon-delete" size="mini" @click="removeTestScript">删除
        </el-button>
      </el-row>
      <el-table :data="form.tableList" border max-height="240" @selection-change="testScriptHandleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="50" label="序号" />
        <el-table-column prop="sourceConnName" label="源服务器" />
        <el-table-column prop="sourceDatabaseName" label="源库名" />
        <el-table-column prop="sourceTableName" label="源表名" />
        <el-table-column prop="whereCondition" label="where条件">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="editWhereCondition(scope.row.whereCondition, scope.$index)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="isSelectTableFlag"
      title="选择迁移数据表"
      width="1400px"
    >
      <div>
        <el-transfer
          v-if="isSelectTableFlag"
          v-model="selectTableList"
          filterable
          :titles="['未确认迁移表清单', '已确认迁移表清单']"
          :format="{ noChecked: '${total}', hasChecked: '${checked}/${total}'}"
          :props="{key: 'pkId', label: 'label'}"
          :data="tableList"
        />
      </div>
      <div slot="footer" class="dialog-footer" style="display: flex; justify-content: center">
        <el-button type="primary" style="margin-right: 30px" @click="submitSelectScript">同意</el-button>
        <el-button @click="cancelSelectScript">取消</el-button>
      </div>
    </el-dialog>

    <!--自定义SQL填写弹窗-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="sqlClose"
      :visible.sync="sqlFlag"
      title="sql语句"
      width="800px"
    >
      <el-form-item label="where条件">
        <el-input v-model="whereCondition" type="textarea" :rows="5" placeholder="请输入" style="width: 540px;" />
      </el-form-item>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="sqlFlag=false">取消</el-button>
        <el-button type="primary" @click="sqlSubmit()">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dataSourceConnApi from '@/api/metadata/dataSource'
import tableTransferListApi from '@/api/data/table/tableTransferList'
import dataSourceApi from '@/api/metadata/dataSource'

export default {
  name: 'ScriptConvertList',
  model: {
    prop: 'form',
    event: 'changes'
  },
  props: {
    form: {
      required: true,
      type: Object
    },
    dialogType: {
      required: true,
      type: Number
    }
  },
  data() {
    return {
      fileList: [],
      isSelectTableFlag: false,
      selectTableList: [],
      tableList: [],
      tmpTableList: [],
      sourceConnList: [],
      sourceDatabaseList: [],
      queryName: null,
      querySourceDatabaseName: null,
      querySourceTableName: null,
      queryTargetDatabaseName: null,
      queryTargetTableName: null,
      selectTestScriptName: [],
      tempDataTransferTableList: [],
      whereCondition: '',
      whereConditionIndex: null,
      sqlFlag: false
    }
  },
  created() {
    this.initData()
  },
  methods: {
    scriptSelectTypeChange(val) {
      if (val === 'exportImport') {
        this.$refs['uploadExcel'].$refs['upload-inner'].handleClick()
      }
    },
    initData() {
      const param = { size: 500, status: 'ENABLE' }
      dataSourceConnApi.findListByPage(param).then(data => {
        this.sourceConnList = data.content
      }).catch(() => {
        this.crud.notify('获取源/目标服务器失败！', 'error')
      })
    },
    dataSourceConnChange(sourceConnPkId) {
      this.form.database = ''
      dataSourceConnApi.schemas(sourceConnPkId).then(res => {
        this.sourceDatabaseList = res
      }).catch(err => {
        console.log(err)
      })
    },
    showScripList() {
      this.resetQuery()
      this.findLatestSuccess()
    },
    showAllTableList() {
      this.resetQuery()
      this.storeAllTables()
    },
    findLatestSuccess() {
      const param = {
        size: 100000,
        status: 'SUCCESS',
        sourceConnPkId: this.form.sourceConnPkId,
        sourceDbName: this.form.database
      }
      tableTransferListApi.findLatestSuccess(param).then(data => {
        this.tableList = []
        if (data.total > 0) {
          this.tmpTableList = data.content
          data.content.forEach(item => {
            const sourceTableName = item.sourceDbName + '.' + item.sourceTableName
            const targetTableName = item.targetDbName + '.' + item.targetTableName
            const label = sourceTableName + ' -> ' + targetTableName
            this.tableList.push({ pkId: item.pkId, label: label })
          })
        }
        this.initselectTableList()
      }).catch((err) => {
        console.log(err)
      })
    },
    storeAllTables() {
      const param = {
        pkId: this.form.sourceConnPkId,
        schema: this.form.database
      }
      dataSourceApi.tables(param).then(data => {
        this.tableList = []
        if (data && data.length > 0) {
          for (let i = 0; i < data.length; i++) {
            this.tableList.push({ pkId: i, label: data[i] })
          }
        }
        this.initselectTableList()
      })
    },
    initselectTableList() {
      if (this.form.transferType === 'ExpandNum') {
        this.selectTableList = []
        this.tableList.forEach(item => {
          this.form.tableList.forEach(item2 => {
            if (item2.tableTransferListPkId === item.pkId) {
              this.selectTableList.push(item.pkId)
            }
          })
        })
      } else {
        this.selectTableList = []
        this.tableList.forEach(item => {
          this.form.tableList.forEach(item2 => {
            if (item2.sourceTableName === item.label) {
              this.selectTableList.push(item.pkId)
            }
          })
        })
      }
      this.isSelectTableFlag = true
    },
    toQuery() {
      if (this.querySourceDatabaseName !== undefined && this.querySourceDatabaseName !== null && this.querySourceDatabaseName !== '') {
        this.tempDataTransferTableList = JSON.parse(JSON.stringify(this.form.tableList))
        this.form.tableList = this.form.tableList.filter((item) => {
          return item.sourceDatabaseName.toUpperCase().includes(this.querySourceDatabaseName.toUpperCase())
        })
      } else if (this.querySourceTableName !== undefined && this.querySourceTableName !== null && this.querySourceTableName !== '') {
        this.tempDataTransferTableList = JSON.parse(JSON.stringify(this.form.tableList))
        this.form.tableList = this.form.tableList.filter((item) => {
          return item.sourceTableName.toUpperCase().includes(this.querySourceTableName.toUpperCase())
        })
      } else if (this.queryTargetDatabaseName !== undefined && this.queryTargetDatabaseName !== null && this.queryTargetDatabaseName !== '') {
        this.tempDataTransferTableList = JSON.parse(JSON.stringify(this.form.tableList))
        this.form.tableList = this.form.tableList.filter((item) => {
          return item.targetDatabaseName.toUpperCase().includes(this.queryTargetDatabaseName.toUpperCase())
        })
      } else if (this.queryTargetTableName !== undefined && this.queryTargetTableName !== null && this.queryTargetTableName !== '') {
        this.tempDataTransferTableList = JSON.parse(JSON.stringify(this.form.tableList))
        this.form.tableList = this.form.tableList.filter((item) => {
          return item.targetTableName.toUpperCase().includes(this.queryTargetTableName.toUpperCase())
        })
      } else {
        this.resetQuery()
      }
    },
    resetQuery() {
      this.querySourceDatabaseName = null
      this.querySourceTableName = null
      this.queryTargetDatabaseName = null
      this.queryTargetTableName = null
      if (this.tempDataTransferTableList !== undefined && this.tempDataTransferTableList.length > 0) {
        this.form.tableList = JSON.parse(JSON.stringify(this.tempDataTransferTableList))
        this.tempDataTransferTableList = []
      }
    },
    // 记录选择的测试脚本
    testScriptHandleSelectionChange(val) {
      this.selectTestScriptName = []
      val.forEach(item => {
        this.selectTestScriptName.push(item.pkId)
      })
    },
    // 删除测试脚本
    removeTestScript() {
      this.selectTestScriptName.forEach(removeId => {
        this.form.tableList.forEach((item, index) => {
          if (removeId === item.pkId) {
            this.form.tableList.splice(index, 1)
          }
        })
        this.selectTableList.forEach((id, index) => {
          if (removeId === id) {
            this.selectTableList.splice(index, 1)
          }
        })
      })
    },
    cancelSelectScript() {
      this.isSelectTableFlag = false
      this.selectTableList = []
    },
    submitSelectScript() {
      this.isSelectTableFlag = false
      this.form.tableList = []
      console.log('迁移表信息', this.tableList)
      this.tableList.forEach((item, index) => {
        let sourceConnName
        if (this.selectTableList.includes(index)) {
          this.sourceConnList.forEach(item => {
            if (item.pkId === this.form.sourceConnPkId) {
              sourceConnName = item.sourceName
            }
          })
          const data = {
            pkId: item.pkId,
            dataTransferTaskPkId: null,
            tableTransferListPkId: null,
            sourceConnPkId: this.form.sourceConnPkId,
            sourceConnName,
            sourceDatabaseName: this.form.database,
            sourceTableName: item.label,
            targetConnPkId: null,
            targetConnName: null,
            targetDatabaseName: null,
            targetTableName: null
          }
          this.form.tableList.push(data)
        }
      })
    },
    getSelectTableInfoById(pkId) {
      let tableInfo = null
      this.tmpTableList.forEach(item => {
        if (item.pkId === pkId) {
          tableInfo = item
        }
      })
      return tableInfo
    },
    // where条件修改提交
    sqlSubmit() {
      this.form.tableList[this.whereConditionIndex].whereCondition = this.whereCondition
      this.sqlFlag = false
    },
    // 编辑where条件
    editWhereCondition(whereCondition, index) {
      this.whereCondition = this.form.tableList[index].whereCondition
      this.whereConditionIndex = index
      this.sqlFlag = true
    },
    // 自定义SQL修改关闭
    sqlClose() {
      this.sqlFlag = false
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-transfer-panel {
  width: 600px !important;
}

::v-deep .bordered-button {
  border: #92dab3 2px;
}

::v-deep .el-transfer__buttons button {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

::v-deep .el-transfer__buttons button:last-child {
  margin-left: 0px;
}
</style>
